/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.fa.in;

//import com.fa.supporters;
import com.fa.supporters.DbConnector;
import com.fa.supporters.PartnerChooserMode;
import com.fa.supporters.TabTablePanel;
import com.fa.supporters.pAddNewProductInput;
import com.fa.supporters.pAddPartnerInput;
import com.fa.supporters.pAddPriceInput;
import com.fa.supporters.pAddTransaction;
import com.fa.supporters.pPartnerChooser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.sql.*;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.netbeans.api.settings.ConvertAsProperties;
import javax.swing.JDesktopPane;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;


/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.fa.in//Buy//EN",
autostore = false)
public final class BuyTopComponent extends TopComponent {

    private static BuyTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "BuyTopComponent";    
    private static JDesktopPane jdkPane;
    
    private JPopupMenu pupMenuTabTable = new JPopupMenu();
    private JMenuItem miCloseTab;
    private JMenuItem miUpdateTab;
    
    public BuyTopComponent() {
        initComponents();
        new DbConnector();
        
        
        //buyJTabbedPane popup menu
        this.miCloseTab = new JMenuItem("Đóng");
        this.miCloseTab.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                BuyTopComponent.
                        this.
                        buyJTabbedPane.
                        remove(BuyTopComponent.
                                        this.buyJTabbedPane.
                                        getSelectedIndex());
            }
        });
        this.pupMenuTabTable.add(miCloseTab);

        this.miUpdateTab = new JMenuItem("Cập nhật");
        this.miUpdateTab.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
//                String strFromDateTime = null;
//                if(jDateChooserFrom.getDate() != null){
//                    strFromDateTime = (new SimpleDateFormat("yyyy-MM-dd")).format(jDateChooserFrom.getDate()) + "00:00:00";
//                }
//                String strToDateTime = null;
//                if(jDateChooserTo.getDate() != null){
//                    strToDateTime = (new SimpleDateFormat("yyyy-MM-dd")).format(jDateChooserTo.getDate()) + "23:59:59";
//                }
//                ((TabTablePanel)BuyTopComponent.
//                        this.
//                        buyJTabbedPane.
//                        getSelectedComponent()).
//                        updateTable(cbxProduct.getSelectedItem().toString(),
//                                    strFromDateTime,
//                                    strToDateTime);
            }
        });
        this.pupMenuTabTable.add(miUpdateTab);
         //----------------------------------------
        
        //this.buyJTabbedPane = TabbedPaneFactory.createCloseButtonTabbedPane();
//        this.buyJTabbedPane.addPropertyChangeListener(TabbedPaneFactory.PROP_CLOSE, new PropertyChangeListener() {
//
//            @Override
//            public void propertyChange(PropertyChangeEvent pce) {
//                JTabbedPane pane = (JTabbedPane)pce.getSource();
//                int sel = pane.getSelectedIndex();
//                JOptionPane.showMessageDialog(null, "add");
//                pane.removeTabAt(sel);
//            }
//        });
        setName(NbBundle.getMessage(BuyTopComponent.class, "CTL_BuyTopComponent"));
        setToolTipText(NbBundle.getMessage(BuyTopComponent.class, "HINT_BuyTopComponent"));

       

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        HostPanel = new javax.swing.JPanel();
        buyJTabbedPane = new javax.swing.JTabbedPane();
        InToolBar = new javax.swing.JToolBar();
        btnAddTransaction = new javax.swing.JButton();
        btnOpenPartnerTab = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnAddPartner = new javax.swing.JButton();
        btnAddProduct = new javax.swing.JButton();
        btnDeletePartner = new javax.swing.JButton();
        btnAddNewInPrice = new javax.swing.JButton();
        btnAddNewOutPrice = new javax.swing.JButton();

        buyJTabbedPane.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                buyJTabbedPaneMouseReleased(evt);
            }
        });

        javax.swing.GroupLayout HostPanelLayout = new javax.swing.GroupLayout(HostPanel);
        HostPanel.setLayout(HostPanelLayout);
        HostPanelLayout.setHorizontalGroup(
            HostPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(buyJTabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE)
        );
        HostPanelLayout.setVerticalGroup(
            HostPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(buyJTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
        );

        InToolBar.setRollover(true);

        btnAddTransaction.setIcon(new javax.swing.ImageIcon("/media/Data/NetBeansWorkspace/FamilyAccounting/Supporters/src/com/fa/icons/AddTransactionIcon.png")); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnAddTransaction, org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddTransaction.text")); // NOI18N
        btnAddTransaction.setToolTipText(org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddTransaction.toolTipText")); // NOI18N
        btnAddTransaction.setFocusable(false);
        btnAddTransaction.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddTransaction.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddTransaction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddTransactionActionPerformed(evt);
            }
        });
        InToolBar.add(btnAddTransaction);

        btnOpenPartnerTab.setIcon(new javax.swing.ImageIcon("/media/Data/NetBeansWorkspace/FamilyAccounting/Supporters/src/com/fa/icons/OpenPartnerTabIcon.png")); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnOpenPartnerTab, org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnOpenPartnerTab.text")); // NOI18N
        btnOpenPartnerTab.setToolTipText(org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnOpenPartnerTab.toolTipText")); // NOI18N
        btnOpenPartnerTab.setFocusable(false);
        btnOpenPartnerTab.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnOpenPartnerTab.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnOpenPartnerTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenPartnerTabActionPerformed(evt);
            }
        });
        InToolBar.add(btnOpenPartnerTab);
        InToolBar.add(jSeparator1);

        btnAddPartner.setIcon(new javax.swing.ImageIcon("/media/Data/NetBeansWorkspace/FamilyAccounting/Supporters/src/com/fa/icons/AddNewPartner.png")); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnAddPartner, org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddPartner.text")); // NOI18N
        btnAddPartner.setToolTipText(org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddPartner.toolTipText")); // NOI18N
        btnAddPartner.setFocusable(false);
        btnAddPartner.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddPartner.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddPartner.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddPartnerActionPerformed(evt);
            }
        });
        InToolBar.add(btnAddPartner);

        btnAddProduct.setIcon(new javax.swing.ImageIcon("/media/Data/NetBeansWorkspace/FamilyAccounting/Supporters/src/com/fa/icons/AddNewProductIcon.png")); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnAddProduct, org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddProduct.text")); // NOI18N
        btnAddProduct.setToolTipText(org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddProduct.toolTipText")); // NOI18N
        btnAddProduct.setFocusable(false);
        btnAddProduct.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddProduct.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddProductActionPerformed(evt);
            }
        });
        InToolBar.add(btnAddProduct);

        btnDeletePartner.setIcon(new javax.swing.ImageIcon("/media/Data/NetBeansWorkspace/FamilyAccounting/Supporters/src/com/fa/icons/DeletePartnerIcon.png")); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(btnDeletePartner, org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnDeletePartner.text")); // NOI18N
        btnDeletePartner.setFocusable(false);
        btnDeletePartner.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnDeletePartner.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDeletePartner.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletePartnerActionPerformed(evt);
            }
        });
        InToolBar.add(btnDeletePartner);

        org.openide.awt.Mnemonics.setLocalizedText(btnAddNewInPrice, org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddNewInPrice.text")); // NOI18N
        btnAddNewInPrice.setFocusable(false);
        btnAddNewInPrice.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddNewInPrice.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddNewInPrice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddNewInPriceActionPerformed(evt);
            }
        });
        InToolBar.add(btnAddNewInPrice);

        org.openide.awt.Mnemonics.setLocalizedText(btnAddNewOutPrice, org.openide.util.NbBundle.getMessage(BuyTopComponent.class, "BuyTopComponent.btnAddNewOutPrice.text")); // NOI18N
        btnAddNewOutPrice.setFocusable(false);
        btnAddNewOutPrice.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAddNewOutPrice.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAddNewOutPrice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddNewOutPriceActionPerformed(evt);
            }
        });
        InToolBar.add(btnAddNewOutPrice);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(InToolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE)
            .addComponent(HostPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(InToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(HostPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnOpenPartnerTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenPartnerTabActionPerformed
        // TODO add your handling code here:
        pPartnerChooser ppc = new pPartnerChooser();
        NotifyDescriptor nd = new NotifyDescriptor(ppc,
                                                   "Chọn khách hàng",
                                                   NotifyDescriptor.OK_CANCEL_OPTION,
                                                   NotifyDescriptor.PLAIN_MESSAGE,
                                                   null,
                                                   NotifyDescriptor.OK_OPTION);
        if(DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.OK_OPTION){
            int selectedID = ppc.getSelectedID();
            String query = "SELECT PartnerName FROM acc_db.Partner WHERE idPartner = " + selectedID;
            try{
                Statement s = DbConnector.mysqlConn.createStatement();
                s.executeQuery(query);
                ResultSet rs = s.getResultSet();
                rs.next();
                String partnerName = rs.getString("PartnerName");
                int tabCount = buyJTabbedPane.getTabCount();
                for(int i=0;i<tabCount;i++){
                    String str = buyJTabbedPane.getTitleAt(i);
                    System.out.println(str);
                    if(str.equalsIgnoreCase(partnerName)){
                        buyJTabbedPane.removeTabAt(i);
                        buyJTabbedPane.insertTab(partnerName, null, new TabTablePanel(selectedID, partnerName), null, i);
                        buyJTabbedPane.setSelectedIndex(i);
                        return;
                    }
                }
                this.buyJTabbedPane.add(partnerName, new TabTablePanel(selectedID, partnerName));
                //this.buyJTabbedPane.add("Test",new TabDisplayer());
                this.buyJTabbedPane.setSelectedIndex(buyJTabbedPane.getTabCount()-1);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_btnOpenPartnerTabActionPerformed

    private void btnAddPartnerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddPartnerActionPerformed
        // TODO add your handling code here:
        pAddPartnerInput api = new pAddPartnerInput();
        NotifyDescriptor nd = new NotifyDescriptor(api,
                                                   "Thêm khách hàng",
                                                   NotifyDescriptor.OK_CANCEL_OPTION,
                                                   NotifyDescriptor.PLAIN_MESSAGE,
                                                   null,
                                                   NotifyDescriptor.OK_OPTION);
        if(DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.OK_OPTION){
            DbConnector.addPartner(api.getPartnerName(), api.getDesc());
        }
    }//GEN-LAST:event_btnAddPartnerActionPerformed

    private void btnAddProductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddProductActionPerformed
        // TODO add your handling code here:
        pAddNewProductInput panpi = new pAddNewProductInput();
        NotifyDescriptor nd = new NotifyDescriptor(panpi,
                                                   "Thêm mã hàng",
                                                   NotifyDescriptor.OK_CANCEL_OPTION,
                                                   NotifyDescriptor.PLAIN_MESSAGE,
                                                   null,
                                                   NotifyDescriptor.OK_OPTION);
        if(DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.OK_OPTION){
            DbConnector.addProduct(panpi.getInProductName(), panpi.getOutProductName());
        }
    }//GEN-LAST:event_btnAddProductActionPerformed

    private void btnDeletePartnerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletePartnerActionPerformed
        // TODO add your handling code here:
        pPartnerChooser ppc = new pPartnerChooser();
        ppc.setMode(PartnerChooserMode.Deleting);
        NotifyDescriptor nd = new NotifyDescriptor(ppc,
                                                   "Xóa khách hàng",
                                                   NotifyDescriptor.OK_CANCEL_OPTION,
                                                   NotifyDescriptor.PLAIN_MESSAGE,
                                                   null,
                                                   NotifyDescriptor.OK_OPTION);
        if(DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.OK_OPTION){
            int selectedID = ppc.getSelectedID();

            if(JOptionPane.showConfirmDialog(null, "Có thực sự muốn xóa khách hàng " + ppc.getPartnerName() + " không?", "Xóa khách hàng", JOptionPane.YES_NO_CANCEL_OPTION) == JOptionPane.YES_OPTION){
                DbConnector.deletePartner(selectedID, ppc.getPartnerName());
            }
        }
    }//GEN-LAST:event_btnDeletePartnerActionPerformed

    private void btnAddNewInPriceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddNewInPriceActionPerformed
        // TODO add your handling code here:
        pAddPriceInput papi = new pAddPriceInput();
        papi.setIsOutPrice(false);
        NotifyDescriptor nd = new NotifyDescriptor(papi, 
                                                   "Giá nhập hàng",
                                                   NotifyDescriptor.OK_CANCEL_OPTION,
                                                   NotifyDescriptor.PLAIN_MESSAGE,
                                                   null,
                                                   NotifyDescriptor.OK_OPTION);
        if(DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.OK_OPTION){
            String date = papi.getDateTimeString();
            DbConnector.addInPrice(date, papi.getProductName(), papi.getPartnerName(), papi.getPrice());
        }
    }//GEN-LAST:event_btnAddNewInPriceActionPerformed

    private void btnAddNewOutPriceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddNewOutPriceActionPerformed
        // TODO add your handling code here:
        pAddPriceInput papi = new pAddPriceInput();
        papi.setIsOutPrice(true);
        NotifyDescriptor nd = new NotifyDescriptor(papi,
                                                   "Giá xuất hàng",
                                                   NotifyDescriptor.OK_CANCEL_OPTION,
                                                   NotifyDescriptor.PLAIN_MESSAGE,
                                                   null,
                                                   NotifyDescriptor.OK_OPTION);
        if(DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.OK_OPTION){
            String date = papi.getDateTimeString();
            DbConnector.addOutPrice(date, papi.getProductName(), papi.getPartnerName(), papi.getPrice());
        }
    }//GEN-LAST:event_btnAddNewOutPriceActionPerformed

    private void btnAddTransactionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddTransactionActionPerformed
        // TODO add your handling code here:
        try{
            pAddTransaction pat = new pAddTransaction(false, this.buyJTabbedPane.getTitleAt(this.buyJTabbedPane.getSelectedIndex()));
            NotifyDescriptor nd = new NotifyDescriptor(pat,
                                                       "Thêm giao dịch",
                                                       NotifyDescriptor.OK_CANCEL_OPTION,
                                                       NotifyDescriptor.PLAIN_MESSAGE,
                                                       null,
                                                       NotifyDescriptor.OK_OPTION);
            if(DialogDisplayer.getDefault().notify(nd) == NotifyDescriptor.OK_OPTION){
                Object[][] data = pat.getData();
                String date;
                String PartnerName;
                String ProductName;
                float quantity;
                String metric;
                String note;
                for(int i=0;i<data.length;i++){
                    for(int j=0;j<data[0].length - 1;j++){
                        if(data[i][j] == null){
                            JOptionPane.showMessageDialog(null, "Không đầy đủ thông tin, ko thêm gì hết!");
                            return;
                        }
                    }
                }
                for(int i=0;i<data.length;i++){
                    date = pat.getDateTime();
                    PartnerName = pat.getPartnerName();
                    ProductName = (String)data[i][0];
                    quantity = Float.parseFloat((String)data[i][1]);
                    metric = (String)data[i][2];
                    //JOptionPane.showMessageDialog(null, metric);
                    note = (String)data[i][3];
                    DbConnector.addTransaction(false, date, PartnerName, ProductName, quantity, metric, note);
                }
                ((TabTablePanel)this.buyJTabbedPane.getSelectedComponent()).updateTable();
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, "Something's wrong");
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnAddTransactionActionPerformed

    private void buyJTabbedPaneMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buyJTabbedPaneMouseReleased
        // TODO add your handling code here:
        if(evt.getButton() == MouseEvent.BUTTON3){
            this.pupMenuTabTable.show(this.buyJTabbedPane, evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_buyJTabbedPaneMouseReleased

    private void createFrame(){
        testJframe tjf = new testJframe();
        tjf.setVisible(true);
        jdkPane.add(tjf);
        try{
            tjf.setSelected(true);
        }catch(java.beans.PropertyVetoException e){
            
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel HostPanel;
    private javax.swing.JToolBar InToolBar;
    private javax.swing.JButton btnAddNewInPrice;
    private javax.swing.JButton btnAddNewOutPrice;
    private javax.swing.JButton btnAddPartner;
    private javax.swing.JButton btnAddProduct;
    private javax.swing.JButton btnAddTransaction;
    private javax.swing.JButton btnDeletePartner;
    private javax.swing.JButton btnOpenPartnerTab;
    private javax.swing.JTabbedPane buyJTabbedPane;
    private javax.swing.JToolBar.Separator jSeparator1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized BuyTopComponent getDefault() {
        if (instance == null) {
            instance = new BuyTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the BuyTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized BuyTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(BuyTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof BuyTopComponent) {
            return (BuyTopComponent) win;
        }
        Logger.getLogger(BuyTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }
}
